<?php

namespace App\Http\Controllers\Report;

use App\Exports\ReportRegionContractExport;
use App\Http\Conf\ResultInfo;
use App\Http\Controllers\Controller;
use App\Http\Models\Business\CacheInvoiceRegionContract;

use App\Http\Models\Report\ReportInvoiceRegionContract;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class RegionContractProgress extends Controller
{
    public function index(Request $request)
    {
        $year = is_numeric($request->year) ? $request->year : date('Y', time());
        $month = is_numeric($request->month) ? $request->month : date('m', time());

        $report_invoice_region_contract = new ReportInvoiceRegionContract($year, $month);

        return view('report.region_contract_progress.index', [
            'year' => $year,
            'month' => $month,
            'report_invoice_region_contract' => $report_invoice_region_contract,
        ]);
    }


    public function cache(Request $request)
    {
        $year = $request->year;
        $month = $request->month;
        //先删除已经缓存的数据
        CacheInvoiceRegionContract::where(['year' => $year, 'month' => $month])->delete();

        //再添加数据
        $invoice_infos = DB::table('invoice_details_sd002')
            ->leftJoin('material', 'invoice_details_sd002.material', '=', 'material.material')
            ->select(['invoice_details_sd002.sales_region_code', 'material.category_contract_id', DB::raw('sum(total_price_no_tax) as amount')])
            ->where([
                'invoice_details_sd002.year' => $year,
                'material.year' => $year,
                'invoice_details_sd002.month' => $month,
            ])->groupBy('invoice_details_sd002.sales_region_code', 'material.category_contract_id')
            ->get()->toArray();

        foreach ($invoice_infos as $invoice_info) {
            $model = new CacheInvoiceRegionContract();
            $model->year = $year;
            $model->month = $month;
            $model->sales_region_code = $invoice_info->sales_region_code;
            $model->category_contract_id  = $invoice_info->category_contract_id;
            $model->amount = $invoice_info->amount;
            $model->save();
        }

        return ['status' => ResultInfo::SUCCESS];
    }


    public function export()
    {
        Excel::store(new ReportRegionContractExport, '/export/大区品类销售进度汇总_' . date('Ymd_His', time()) . '.xlsx');
        return ['status' => ResultInfo::SUCCESS];
    }
}
